#include "GLApp.h"
namespace mp_gl
{

	/*===========================================
	GLApp
	============================================*/

	GLApp::GLApp(bool networkThreadEnabled)
		:Drawable()
	{
		m_ac = new GLAppComponents();
		m_scene = NULL;
		m_networkThreadEnabled = networkThreadEnabled;
	}

	GLApp::~GLApp()
	{
		delete m_ac;
	}

	void GLApp::Initialize()
	{
		//Initialize Components
		m_ac->m_glWindow->Initialize();
		m_ac->m_glInput->Initialize();
		//m_ac->m_audio->Initialize();
		m_ac->m_network->Initialize();

		//Initialize Scene
		if (m_scene != NULL)	
			if(!m_scene->IsInitialized())
				m_scene->Initialize();



		//Finally, set the operation flags
		m_initialized = true;
		m_running = true;
	}

	void GLApp::Uninitialize()
	{
		if (m_scene != NULL)
			if(m_scene->IsInitialized())
				m_scene->Uninitialize();

		m_ac->m_network->Uninitialize();
		//m_ac->m_audio->Uninitialize();
		m_ac->m_glInput->Uninitialize();
		m_ac->m_glWindow->Uninitialize();

		//Finally, set the operation flags
		Updateable::Uninitialize();
	}

	void GLApp::LoadContent()
	{
		if (m_scene != NULL)
			if(!m_scene->IsContentLoaded())
				m_scene->LoadContent();

		//Finally, set the operation flags
		m_contentLoaded = true;
	}
	
	void GLApp::UnloadContent()
	{
		if (m_scene != NULL)
			if(m_scene->IsContentLoaded())
				m_scene->UnloadContent();

		//Finally, set the operation flags
		m_contentLoaded = false;
		m_visible = false;
	}
	
	void GLApp::Update()
	{
		//Check for manual window close
		if ( m_ac->m_glWindow->ShouldClose() )
			m_running = false;

		//Get events
		glfwPollEvents();
	
		m_ac->m_glWindow->Update();
		m_ac->m_glInput->Update();
		//m_ac->m_audio->Update();
		if ( !m_networkThreadEnabled )
			m_ac->m_network->Update();

		if (m_scene != NULL)
			m_scene->Update();
	}
	
	void GLApp::UpdateLogic()
	{
		m_scene->UpdateLogic();
	}

	void GLApp::Draw()
	{
		if (m_scene != NULL)
			m_scene->Draw();

		m_ac->m_glWindow->SwapBuffers();
	}

	void GLApp::LoadScene(GLAppScene* scene)
	{
		if (m_scene != NULL)
			UnloadCurrentScene();
		m_scene = scene;
		m_scene->SetAppComponents(m_ac);
		//If the application is already initialized
		if ( IsInitialized() )
			if(!m_scene->IsInitialized())
				m_scene->Initialize();
		//If the application has already loaded content
		if ( IsContentLoaded() )
			if(!m_scene->IsContentLoaded())
				m_scene->LoadContent();
		int x = 1;
		return;
	}

	void GLApp::UnloadCurrentScene()
	{
		if (m_scene != NULL)
		{
			if(m_scene->IsContentLoaded())
				m_scene->UnloadContent();
			if(m_scene->IsInitialized())
				m_scene->Uninitialize();
			m_scene = NULL;
		}
	}

}